package _2022.hot100._20_有效的括号;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @author： YHSimon
 * @date： 2022-03-20 16:53
 */
public class Solution {
    //栈
    public boolean isValid(String s) {
        //优化
        int n = s.length();
        if (n % 2 == 1) {
            return false;
        }
        char[] chars = s.toCharArray();
        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            if (chars[i] == '(' || chars[i] == '[' || chars[i] == '{') {
                stack.push(chars[i]);
            } else {
                if (!stack.isEmpty()) {
                    char tmp = stack.peek();
                    if ((tmp == '(' && chars[i] == ')') || (tmp == '[' && chars[i] == ']') || (tmp == '{' && chars[i] == '}')) {
                        stack.pop();
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    // 官方
    public boolean isValid2(String s) {
        int n = s.length();
        if (n % 2 == 1) {
            return false;
        }
        Map<Character, Character> pairs = new HashMap<Character, Character>() {{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Deque<Character> stack = new LinkedList<Character>();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if (pairs.containsKey(ch)) {
                if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }


    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.isValid("{[]]"));
    }
}
